<template>
  <div class="filter-model" id="ContainerModul-T">
    <i class="myicon icon-filter header-icon" id="ContainerMain-T"></i>
    <template v-for="(tag,i) in filterData">
      <el-tag
        v-if="tag.type==='search'"
        style="cursor: pointer"
        :key="i"
        size="small"
        closable
        :disable-transitions="true"
        @close="removeFilterNode(i)"
        @click="editTransferByTag(tag,i)"
      >
        {{ formatTagText(tag) }}
      </el-tag>
      <el-popover
        v-else
        :key="i"
        placement="bottom"
        trigger="click">
        <el-tag
          slot="reference"
          style="cursor: pointer"
          :key="i"
          size="small"
          closable
          :disable-transitions="true"
          @close="removeFilterNode(i)"
        >
          {{ formatTagText(tag) }}
        </el-tag>
        <el-input size="mini" v-if="tag.type === 'input'" v-model.trim="filterData[i].value"
                  id="containerElInput-T"></el-input>
        <el-select v-else v-model="filterData[i].value" size="mini"
                   multiple
                   clearable
                   collapse-tags
                   filterable
                   id="ElSelctButton-T"
                   class="button-new-tag"
                   :ref="'saveTagInput'+[i]">
          <el-option
            v-for="item in selectOptions(tag)"
            :key="item.value"
            :label="item.label"
            :value="{label:item.label, value: item.value}"
            filterable>
          </el-option>
        </el-select>
      </el-popover>
    </template>
    <el-cascader
      class="button-new-tag"
      v-model="cascaderValue"
      :options="options"
      size="mini"
      :props="{ expandTrigger: 'hover' }"
      filterable
      id="ContainerElTopButton-T"
      placeholder="添加筛选条件"
      @change="handleChangeCascader"
    ></el-cascader>
    <!--输入搜索框弹窗-->
    <el-dialog
      :visible.sync="searchDialogVisible"
      append-to-body
      id="ElDialongSerch-T"
      :modal="false"
      :close-on-click-modal="false"
      width="800px"
      @close="clearDialogInput"
    >
      <cs-transfer :roles="queryList" ref="transferRef" v-model="searchValue" id="ElFooterButton-T"></cs-transfer>
      <span slot="footer" class="dialog-footer">
    <el-button size="mini" type="primary" @click="submitFilterQuery" id="FooterClickButtonOne-T">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      :visible.sync="inputDialogVisible"
      append-to-body
      :modal="false"
      :close-on-click-modal="false"
      width="300px"
      @close="input=''"
    >
      <el-input size="mini" v-model.trim="input" placeholder="请输入内容" ref="inputRef"
                @keyup.enter.native="submitInput"></el-input>
      <span slot="footer" class="dialog-footer">
    <el-button size="mini" type="primary" @click="submitInput" id="FooterClickButtonTow-T">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import CsTransfer from "@/components/CsTransfer/CsTransfer";
import {debounce} from 'lodash'

export default {
  name: "CsFilterQuery",
  props: {
    options: {
      type: Array,
      default() {
        // [{
        //   value: 'platform', // 唯一
        //   label: '媒体',
        //   children: [
        //     {
        //       value: 'a',
        //       label: '媒体'
        //     }
        //   ]
        // }, {
        //   value: 'os',
        //   label: '系统',
        //   queryList: [{
        //     value: 'os',
        //     label: '系统',
        //   }]
        // }]
        return []
      }
    },
  },
  components: {
    CsTransfer
  },
  data() {
    return {
      cascaderValue: [],
      // 搜索传递框的多选配置，类似select组件配置
      roles: [],
      // 已选择原始数据，驱动tag组件生成
      filterData: [],
      // 搜索框弹窗
      searchDialogVisible: false,
      // 搜索框传递数据
      searchDialogData: {
        title: '',
        label: '', // 弹窗数值缓存
        value: '' // 废弃
      },
      // 搜索弹窗数值
      searchValue: [],
      // 弹窗是否为修改
      isEdit: false,
      // 当前弹窗的索引
      currentQueryIndex: '',
      queryList: [],
      inputDialogVisible: false,
      input: ''
    }
  },
  computed: {
    formatFilterData() {
      const data = new Object()
      this.filterData.forEach(item => {
        if (data.hasOwnProperty(item.label)) {
          if (item.type === 'input') {
            data[item.label] = item.value
          } else {
            // 去重
            data[item.label] = Array.from(new Set([...data[item.label].split(','), ...item.value.map(item => item.value)])).join(',')
          }
        } else {
          if (item.type === 'input') {
            data[item.label] = item.value
          } else {
            data[item.label] = item.value.map(item => item.value).join(',')
          }
        }
      })
      return data
    }
  },
  watch: {
    filterData: {
      handler: debounce(function (val, oldVal) {
        this.$emit('change', this.formatFilterData)
      }, 500),
      deep: true
    }
  },
  methods: {
    // 筛选条件改变
    handleChangeCascader(values) {
      const index = this.filterData.findIndex(item => {
        return item.label === values[0]
      })
      if (values.length === 1) {
        // 级联选择框一级选择
        this.isEdit = false

        this.searchDialogData.title = this.options.find(item => item.value === values[0]).label
        this.searchDialogData.label = values[0]
        if (this.options.find(item => item.value === values[0]).hasOwnProperty('queryList')) {
          this.queryList = this.options.find(item => item.value === values[0]).queryList
          this.searchDialogVisible = true
          this.$nextTick(() => {
            this.$refs.transferRef.$refs.input.focus()
          })
        } else {
          this.inputDialogVisible = true
          this.$nextTick(() => {
            this.$refs.inputRef.focus()
          })
        }
        // this.$emit('click-one-level',values[0])
      } else if (values.length === 2) {
        // 级联选择二级菜单
        const group = this.options.find(item => item.value === values[0])
        if (index === -1) {
          this.filterData.push({
            label: values[0],
            value: group.children.filter(item => item.value === values[1]),
            level: 2 // 类型1为一级，类型2为二级
          })
        } else {
          if (!this.filterData[index].value.some(item => item.value === values[1])) {
            this.filterData[index].value.push(group.children.find(item => item.value === values[1]))
          }
        }
      }
      this.cascaderValue = []
    },
    // 选择菜单
    selectOptions(tag) {
      const group = this.options.find(item => item.value === tag.label)
      return group.children
    },
    // 格式筛选标签显示
    formatTagText(tag) {
      // 查询出类型
      const group = this.options.find(item => item.value === tag.label)
      // 类型下面子类过滤。变化。瓶装成字符串
      let values = ''
      if (tag.value instanceof Array) {
        values = tag.value.map(item => item.label).join('，')
      } else {
        values = tag.value
      }
      // 拼接 搜索类型：子类内容，子类内容
      let text = group.label + '：' + values
      if (text.length > 50) { // 限制50个字
        text = text.substr(0, 50) + '...'
      }
      return text
    },
    //移除搜索节点
    removeFilterNode(index) {
      this.filterData.splice(index, 1)
    },
    // 提交筛选条件
    submitFilterQuery() {
      if (this.isEdit) {
        if (this.searchValue.length === 0) {
          this.filterData.splice(this.currentQueryIndex, 1)
        } else {
          this.filterData[this.currentQueryIndex].value = this.searchValue
        }
      } else {
        const index = this.filterData.findIndex(item => item.label === this.searchDialogData.label)
        if (index === -1) {
          if (this.searchValue.length === 0) return
          this.filterData.push({
            label: this.searchDialogData.label,
            value: this.searchValue,
            type: 'search',
            level: 1
          })
        } else {
          const arr = this.filterData[index].value.concat(this.searchValue)
          const hash = {};
          const newArr = arr.reduce((item, next) => {
            hash[next.value] ? '' : hash[next.value] = true && item.push(next);
            return item
          }, []);
          this.filterData[index].value = newArr
        }
      }
      this.searchDialogVisible = false
      // console.log(this.filterData)
    },
    // 修改搜索标签
    editTransferByTag(tag, index) {
      // const group = this.filterData[i]
      this.isEdit = true
      this.currentQueryIndex = index
      this.searchValue = tag.value
      this.queryList = this.options.find(item => item.value === tag.label).queryList

      this.searchDialogVisible = true
    },
    // 清空弹窗输入内容
    clearDialogInput() {
      this.$refs.transferRef.searchTextLeft = ''
      this.$refs.transferRef.originData = []
      this.searchValue = []
      this.input = ''
    },
    // 清除数据
    clear() {
      this.filterData = []
    },
    // 提交输入框
    submitInput() {
      if (this.input === '') return
      const index = this.filterData.findIndex(item => item.label === this.searchDialogData.label)
      if (index === -1) {
        this.filterData.push({
          label: this.searchDialogData.label,
          value: this.input,
          level: 1,
          type: 'input'
        })
      } else {
        this.filterData[index].value = this.input
      }
      this.inputDialogVisible = false
    },
    // 配置反显值
    setFilterData(data) {
      this.filterData = []
      for (const dataKey in data) {
        const obj = this.options.find(item => item.value === dataKey)
        const inclueArr = data[dataKey].split(',')
        if (obj.hasOwnProperty('queryList')) {
          this.filterData.push({
            label: dataKey,
            value: obj.queryList.filter(item => {
              return inclueArr.includes(item.value)
            }),
            type: 'search',
            level: 1
          })
        } else if (obj.hasOwnProperty('children')) {
          this.filterData.push({
            label: dataKey,
            value: obj.children.filter(item => {
              return inclueArr.includes(item.value)
            }),
            level: 2
          })
        } else {
          this.filterData.push({
            label: dataKey,
            value: data[dataKey],
            type: 'input',
            level: 1
          })
        }
      }
      console.log(this.filterData)
    }
  }
}
</script>

<style scoped>
.header-icon {
  font-size: 20px;
  color: #00a2ff
}

.el-tag {
  margin-left: 10px;
  margin-bottom: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-bottom: 10px;
}

</style>
